package com.hliushi.netty.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author llhuang10
 * @date 2021/10/18 22:19
 */
@Slf4j
public class CloseFutureClient {

    public static void main(String[] args) throws InterruptedException {
        Scanner scanner = new Scanner(System.in);
        NioEventLoopGroup group = new NioEventLoopGroup();
        // 2.带有Future, Promise的类型都是和异步方法配套使用, 用户处理结果
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    // 在连接建立后被调用
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                // 1.连接到服务器
                // connect异步非阻塞, main发起了调用, 真正执行connect是nio线程
                .connect(new InetSocketAddress("localhost", 10010));

        channelFuture.sync();
        Channel channel = channelFuture.channel();
        log.debug("{}", channel);

        new Thread(() -> {

            while (true) {
                String line = scanner.nextLine();
                if ("q".equals(line)) {
                    // channel.close()请求关闭Channel并在操作完成后通知ChannelFuture
                    channel.close();    // close异步操作, 可能在1s之后完成关闭 |
                    // log.debug("处理关闭之后的操作"); // 不能在这里处理善后操作
                    break;
                }
                channel.writeAndFlush(line);
            }
        }, "input").start();

        // 获取CloseFuture对象
        ChannelFuture closeFuture = channel.closeFuture();
        // 1) 同步处理关闭(控制两个线程谁先谁后) --> 关闭操作在nio线程, 善后操作在main线程
        // log.debug("waiting close ....");
        // closeFuture.sync();
        // log.debug("处理关闭之后的操作");
        // scanner.close();

        // 2) 异步处理关闭    --->  关闭操作和善后操作都是nio的线程来处理
        closeFuture.addListener((ChannelFutureListener) future -> {
            log.debug("处理关闭之后的操作");
            scanner.close();
            group.shutdownGracefully();
        });
    }
}
